import React, { useState, useCallback, useEffect, useRef } from 'react';
interface IProp {
  visible: boolean; // 计时器是否清除，为false停止
}
/**当前时间 */
const NowTime: React.FC<IProp> = (props: IProp) => {
  const [nowTime, setNowTime] = useState<string>('');
  const timer = useRef<any>(null);
  // 获取时间
  const getNowTime = useCallback(() => {
    const today = new Date();
    const todayTime = formatDateTime(today);
    const words = todayTime + ' 周' + '日一二三四五六'.charAt(today.getDay());
    // console.log(words);
    setNowTime(words);
  }, []);
  useEffect(() => {
    // console.log(props.visible, "now-time-计时器-开关");
    clearInterval(timer.current);
    if (props.visible) {
      timer.current = setInterval(() => {
        getNowTime();
      }, 1000);
    }
  }, [getNowTime, props.visible]);

  // 格式化当前时间，格式 时:分:秒 年-月-日 周X
  const formatDateTime = (date: any) => {
    const y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? '0' + m : m;
    let d = date.getDate();
    d = d < 10 ? '0' + d : d;
    let h = date.getHours();
    h = h < 10 ? '0' + h : h;
    let minute = date.getMinutes();
    minute = minute < 10 ? '0' + minute : minute;
    let second = date.getSeconds();
    second = second < 10 ? '0' + second : second;
    return h + ':' + minute + ':' + second + ' ' + y + '-' + m + '-' + d;
  };

  return <div className="now-time">{nowTime}</div>;
};
export default NowTime;
